package com.zxl.yunpicture.interfaces.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxl.yunpicture.application.service.SpaceApplicationService;
import com.zxl.yunpicture.application.service.UserApplicationService;
import com.zxl.yunpicture.domain.space.entity.Space;
import com.zxl.yunpicture.domain.space.valueObject.SpaceLevelEnum;
import com.zxl.yunpicture.domain.user.constant.UserConstant;
import com.zxl.yunpicture.domain.user.entity.User;
import com.zxl.yunpicture.infrastructure.annotation.AuthCheck;
import com.zxl.yunpicture.infrastructure.common.BaseResponse;
import com.zxl.yunpicture.infrastructure.common.DeleteRequest;
import com.zxl.yunpicture.infrastructure.common.ResultUtils;
import com.zxl.yunpicture.infrastructure.exception.BusinessException;
import com.zxl.yunpicture.infrastructure.exception.ErrorCode;
import com.zxl.yunpicture.infrastructure.exception.ThrowUtils;
import com.zxl.yunpicture.interfaces.assembler.SpaceAssembler;
import com.zxl.yunpicture.interfaces.dto.space.*;
import com.zxl.yunpicture.interfaces.vo.space.SpaceVO;
import com.zxl.yunpicture.shared.auth.SpaceUserAuthManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/space")
public class SpaceController {

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private SpaceApplicationService spaceApplicationService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    /**
     * 创建空间
     * @param spaceAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addSpace(@RequestBody SpaceAddRequest spaceAddRequest, HttpServletRequest request){
        ThrowUtils.throwIf(spaceAddRequest == null,ErrorCode.PARAMS_ERROR);
        User loginUser = userApplicationService.getLoginUser(request);
        long newId = spaceApplicationService.addSpace(spaceAddRequest, loginUser);
        return ResultUtils.success(newId);
    }


    /**
     * 删除空间
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSpace(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request){
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0,ErrorCode.PARAMS_ERROR);
        spaceApplicationService.deleteSpace(deleteRequest,request);
        return ResultUtils.success(true);
    }

    /**
     * 更新空间 仅管理员可用
     * @param spaceUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateSpace(@RequestBody SpaceUpdateRequest spaceUpdateRequest, HttpServletRequest request){
        ThrowUtils.throwIf(spaceUpdateRequest == null || spaceUpdateRequest.getId() <= 0,ErrorCode.PARAMS_ERROR);
        //将实体类和DTO进行转换
        Space space = SpaceAssembler.toSpaceEntity(spaceUpdateRequest);
        //自动填充数据
        spaceApplicationService.fillSpaceBySpaceLevel(space);
        //数据校验
        space.validSpace(false);
        //判断是否存在 先看老数据是否存在
        Long id = spaceUpdateRequest.getId();
        Space oldSpace = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(oldSpace == null,ErrorCode.NOT_FOUND_ERROR);
        //操作数据库
        boolean result = spaceApplicationService.updateById(space);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据id获取空间 仅管理员可用
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Space> getSpaceById(long id,HttpServletRequest request){
        ThrowUtils.throwIf(id <= 0,ErrorCode.PARAMS_ERROR);
        //查询数据库
        Space space = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(space);
    }

    /**
     * 根据id获取空间 给用户用
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SpaceVO> getSpaceVOById(long id,HttpServletRequest request){
        ThrowUtils.throwIf(id <= 0,ErrorCode.PARAMS_ERROR);
        Space space = spaceApplicationService.getById(id);
        SpaceVO spaceVO = spaceApplicationService.getSpaceVO(space, request);
        User loginUser = userApplicationService.getLoginUser(request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        spaceVO.setPermissionList(permissionList);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(spaceVO);
    }


    /**
     * 分页获取空间列表 仅管理员使用
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Space>> listSpaceByPage(@RequestBody SpaceQueryRequest spaceQueryRequest){
        long current = spaceQueryRequest.getCurrent();
        long pageSize = spaceQueryRequest.getPageSize();
        //查询数据库
        Page<Space> spacePage = spaceApplicationService.page(new Page<>(current,pageSize),
                spaceApplicationService.getQueryWrapper(spaceQueryRequest));
        return ResultUtils.success(spacePage);
    }

    /**
     * 分页获取空间列表 （封装类）
     * @param spaceQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    //@AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<SpaceVO>> listSpaceVOByPage(@RequestBody SpaceQueryRequest spaceQueryRequest,
                                                           HttpServletRequest request){
        long current = spaceQueryRequest.getCurrent();
        long pageSize = spaceQueryRequest.getPageSize();
        //限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);
        //查询数据库
        Page<Space> spacePage = spaceApplicationService.page(new Page<>(current,pageSize),
                spaceApplicationService.getQueryWrapper(spaceQueryRequest));
        //获取封装类
        return ResultUtils.success(spaceApplicationService.getSpaceVOPage(spacePage,request));
    }

    /**
     * 编辑空间信息
     * @param spaceEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSpace(@RequestBody SpaceEditRequest spaceEditRequest, HttpServletRequest request){
        if(spaceEditRequest == null || spaceEditRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //在此处将实体类和DTO进行转换
        Space space = SpaceAssembler.toSpaceEntity(spaceEditRequest);
        //自动填充数据
        spaceApplicationService.fillSpaceBySpaceLevel(space);
        //设置编辑时间
        space.setEditTime(new Date());
        //数据校验
        space.validSpace(false);
        User loginUser = userApplicationService.getLoginUser(request);
        //判断是否存在
        Long id = spaceEditRequest.getId();
        Space oldSpace = spaceApplicationService.getById(id);
        ThrowUtils.throwIf(oldSpace == null,ErrorCode.NOT_FOUND_ERROR);
        //仅本人或管理员可以编辑
        spaceApplicationService.checkSpaceAuth(loginUser,oldSpace);
        //操作数据库
        boolean result = spaceApplicationService.updateById(space);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 获取空间级别列表，便于前端展示
     * @return
     */
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> listSpaceLevel(){
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize()
                ))
                .collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }

}
